import React from 'react';
import { Form, Input, Checkbox, Tag, Table, message } from 'antd';
import { BorderOuterOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import CommonModalForm from '@/components/CommonModalForm';
import {
  queryactivityList,
  queryrecruitList,
  querysendcouponList,
  querylotterydrawList,
  queryinviteList,
} from '@/services/management.service';
import { activityInfo, listType } from './type';
import './index.less';

type TProps = {
  visible: boolean;
  confirmLoading: boolean;
  selectActivityInfo: activityInfo;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
};

const ChooseActivities: React.FC<TProps> = (props) => {
  const { visible, confirmLoading, selectActivityInfo, onCancel, onSubmit } = props;
  const [form] = Form.useForm();
  const [selectTopCate, setSelectTopCate] = React.useState<string>('');
  const [selectSecoundCate, setSelectSecoundCate] = React.useState<string>('');
  const [secoundInfo, setSecoundInfo] = React.useState<any>({});
  const [activityId, setActivityId] = React.useState(-1);
  const [activities, setActivities] = React.useState<any[]>([]);
  const [list, setList] = React.useState<listType[]>([]);

  const interfaceInfo: any = {
    领券活动: {
      name: querysendcouponList,
      params: { page: 1, pageSize: 10, status: 3 },
      path: '/pages/activity/RedPacket/index',
    },
    抽奖活动: {
      name: querylotterydrawList,
      params: { page: 1, pageSize: 10, status: 3 },
      path: '/pages/activity/DrawLottery/index',
    },
    新人活动: {
      name: queryrecruitList,
      params: { status: 1 },
      path: '/pages/activity/RegistGift/index',
    },
    老拉新活动: {
      name: queryinviteList,
      params: { page: 1, pageSize: 10, status: 3 },
      path: '/pages/activity/InviteActivity/index',
    },
  };

  const init = async () => {
    const params: any = {};
    try {
      const { code, message: msg, data } = await queryactivityList(params);
      if (code === 0) {
        const defaultDatas: any = [];
        if (data.length > 0) {
          data.forEach((ele: any, index: number) => {
            defaultDatas.push({
              name: ele.type,
              id: Math.random().toString(36).substr(2),
              children: [],
            });
            ele.nodes.forEach((item: any, num: number) => {
              defaultDatas[index].children.push({
                value: item.activityTypeName,
                id: Math.random().toString(36).substr(2),
                url: item.apiUrl,
              });
            });
          });
          setList(defaultDatas);
        }
      } else {
        message.error(msg);
      }
    } catch (error) {}
  };

  React.useEffect(() => {
    init();
  }, []);

  // 编辑进来
  React.useEffect(() => {
    if (selectActivityInfo.id) {
      setActivityId(selectActivityInfo.id);
    } else {
      setActivityId(-1);
    }
  }, [selectActivityInfo]);

  React.useEffect(() => {
    // 根据一二级分类筛选商品
    if (selectTopCate && selectSecoundCate) {
      const topIndex = list.findIndex((item: listType) => item.id === selectTopCate);
      const secoundIndex = list[topIndex].children.findIndex(
        (item: any) => item.id === selectSecoundCate,
      );
      setActivities(list?.[topIndex]?.children?.[secoundIndex]?.activities || []);
    }
  }, [selectTopCate, selectSecoundCate]);

  // 取消
  const handleCancel = () => {
    if (selectActivityInfo.id !== activityId) {
      setActivityId(selectActivityInfo.id);
    }
    onCancel();
  };

  // 选择一级分类
  const handleChooseTopCate = (item: any) => {
    setSelectTopCate(item.id);
  };

  // 查询活动
  const findActivity = async (info: any) => {
    const {
      code,
      message: msg,
      data,
    } = await interfaceInfo[info.value].name(interfaceInfo[info.value].params);

    if (code === 0) {
      if (data.data.length > 0) {
        const options: any = [];
        data.data.forEach((ele: any) => {
          options.push(ele);
        });
        setActivities(options);
      }
    } else {
      message.error(msg);
    }
  };

  // 选择二级分类
  const handleChooseSecoundCate = (val: any) => {
    findActivity(val);
    setSecoundInfo(val);
    setSelectSecoundCate(val.id);
  };

  // 选择活动
  const handleChange = (e: any) => {
    setActivityId(e.target.value);
  };

  const handleSubmit = () => {
    const obj = activities.find((item) => (item.activityId || item.id) === activityId);
    const info = {
      id: activityId,
      title: obj.name || obj.activityName,
      path: interfaceInfo[secoundInfo.value].path,
    };
    onSubmit(info);
  };

  const columns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      render: (_: object, record: any) => (
        <>
          <div className="selectActivitiesItem">
            <Checkbox
              value={record.activityId || record.id}
              onChange={handleChange}
              checked={(record.activityId || record.id) === activityId}
            >
              <div className="activitiesInfo">
                <span className="activitiesName">{record.activityName || record.name}</span>
                <span className="activitiesId">{record.activityId || record.id}</span>
              </div>
            </Checkbox>
          </div>
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: () => (
        <>
          <Tag color="green">正式发布</Tag>
        </>
      ),
    },
    {
      title: '起止时间',
      dataIndex: 'creatTime',
      key: 'creatTime',
      render: (_: object, record: any) => (
        <>
          <div>
            {record.creatTime || record.activityStartTime}至
            {record.endTime || record.activityEndTime}
          </div>
        </>
      ),
    },
  ];

  // 搜索
  const handleInputChange = async (e: any) => {
    if (Object.keys(secoundInfo).length > 0) {
      const {
        code,
        message: msg,
        data,
      } = await interfaceInfo[secoundInfo.value].name({
        ...interfaceInfo[secoundInfo.value].params,
        idOrName: e.target.value,
      });

      if (code === 0) {
        const options: any = [];
        data.data.forEach((ele: any) => {
          options.push(ele);
        });
        setActivities(options);
      } else {
        message.error(msg);
      }
    }
  };

  return (
    <CommonModalForm
      formRef={form}
      visible={visible}
      confirmLoading={confirmLoading}
      okText={'确定'}
      title={'选择活动'}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
      width={1000}
      formProps={{
        layout: 'vertical',
        autoComplete: 'off',
      }}
      okButtonProps={{
        disabled: !(selectTopCate && selectSecoundCate && activityId > -1),
      }}
    >
      <div className="chooseContent">
        <div className="chooseActivities">
          {/* 分类 */}
          <div className="selectActivitiesCate">
            {list.map((item) => (
              <div className="cateContent" key={item.id}>
                {/* 一级分类 */}
                <div
                  className={`topCate ${selectTopCate === item.id && 'selectTopCate'}`}
                  onClick={() => handleChooseTopCate(item)}
                >
                  <BorderOuterOutlined className="cateIcon" />
                  <span className="cateName">{item.name}</span>
                  {selectTopCate === item.id ? (
                    <DownOutlined className="cateArrow" />
                  ) : (
                    <UpOutlined className="cateArrow" />
                  )}
                </div>
                {/* 二级分类 */}
                <div
                  className="secoundCateContent"
                  style={{ height: selectTopCate === item.id ? 'auto' : '0' }}
                >
                  {item.children.map((val: any) => (
                    <div
                      className={`secoundCate ${
                        selectSecoundCate === val.id && 'selectSecoundCate'
                      }`}
                      key={val.id}
                      onClick={() => handleChooseSecoundCate(val)}
                    >
                      {val.value}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
          <div className="selectActivities">
            <div className="searchInt">
              <Input
                className="int"
                type="text"
                placeholder="请输入要查找的活动名或活动ID"
                onChange={handleInputChange}
              />
            </div>
            <Table columns={columns} dataSource={activities} pagination={false} />
          </div>
        </div>
      </div>
    </CommonModalForm>
  );
};

export default ChooseActivities;
